package cn.zhaoyuening.zshop4j.content.service.impl;

import cn.zhaoyuening.zshop4j.common.bean.EasyUiTreeNode;
import cn.zhaoyuening.zshop4j.common.bean.ZShop4jResponceResult;
import cn.zhaoyuening.zshop4j.common.utils.JsonUtils;
import cn.zhaoyuening.zshop4j.content.service.ContentCategoryService;
import cn.zhaoyuening.zshop4j.manager.mapper.TbContentCategoryMapper;
import cn.zhaoyuening.zshop4j.manager.pojo.TbContentCategory;
import cn.zhaoyuening.zshop4j.manager.pojo.TbContentCategoryExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zhao on 2017/4/12.
 */
@Service("contentCategoryService")
public class ContentCategoryServiceImpl implements ContentCategoryService{
    @Autowired
    private TbContentCategoryMapper contentCategoryMapper;

    @Override
    public List<EasyUiTreeNode> getContentCategoryList(long parentId) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        example.createCriteria().andParentIdEqualTo(parentId);
        List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
        return contentCategory2EasyUiTreeNodeList(list);
    }

    @Override
    public ZShop4jResponceResult insert(TbContentCategory contentCategory) {
        ZShop4jResponceResult result = null;
        int insertResult = contentCategoryMapper.insertSelective(contentCategory);
        if (insertResult > 0) {
            result = ZShop4jResponceResult.ok();
            result.setData(contentCategory.getId());
        }else{
            result = ZShop4jResponceResult.build(500,"创建类型失败！");
        }

        return result;
    }

    @Override
    public ZShop4jResponceResult delete(TbContentCategory contentCategory) {
        int deleteResult = contentCategoryMapper.deleteByPrimaryKey(contentCategory.getId());
        if (deleteResult > 0) {
            return ZShop4jResponceResult.ok();
        }
        return ZShop4jResponceResult.fail();
    }

    @Override
    public ZShop4jResponceResult update(TbContentCategory contentCategory) {
        int updateResult = contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
        if (updateResult > 0) {
            return ZShop4jResponceResult.ok();
        }
        return ZShop4jResponceResult.fail();
    }


    private List<EasyUiTreeNode> contentCategory2EasyUiTreeNodeList(List<TbContentCategory> list) {
        List<EasyUiTreeNode> easyUiTreeNodeList = new ArrayList<>();
        for (TbContentCategory contentCategory:
             list) {
            EasyUiTreeNode node = new EasyUiTreeNode();
            node.setId(contentCategory.getId());
            node.setText(contentCategory.getName());
            node.setState(contentCategory.getIsParent());
            easyUiTreeNodeList.add(node);
        }
        return easyUiTreeNodeList;
    }
}
